package com.xinchuang.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinchuang.comment.R;
import com.xinchuang.entity.User;
import com.xinchuang.entity.train.TrainImg;
import com.xinchuang.mapper.UserMapper;
import com.xinchuang.mapper.train.TrainImgMapper;
import com.xinchuang.service.PhotoService;
import com.xinchuang.service.RedisUseService;
import com.xinchuang.service.UserService;
import com.xinchuang.service.train.TrainImgService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;

@Service
@RequiredArgsConstructor
public class PhotoServiceImpl implements PhotoService {

    private static DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private final TrainImgService trainImgService;

    private final TrainImgMapper trainImgMapper;

    private final UserMapper userMapper;

    private final RedisUseService redisUseService;

    @Override
    public String imgList(JSONObject jsonObject) {
        //jsonobject解析获取页码
        String pageNum = jsonObject.getString("pageNum");
        //jsonobject解析获取页容
        String pageSize = jsonObject.getString("pageSize");
        //jsonobject解析获取图片名称
        String imgName = jsonObject.getString("imgName");

        LambdaQueryWrapper<TrainImg> trainImgWrapper = new LambdaQueryWrapper<>();
        trainImgWrapper.like(StringUtils.isNotEmpty(imgName), TrainImg::getImgNameOne, imgName).
                or().like(StringUtils.isNotEmpty(imgName), TrainImg::getImgNameTwo, imgName)
                .orderByDesc(TrainImg::getSort);
        Page<TrainImg> trainImgPage = new Page<TrainImg>(Long.valueOf(pageNum), Long.valueOf(pageSize));
        IPage<TrainImg> trainImgIPage = trainImgService.page(trainImgPage, trainImgWrapper);
        List<TrainImg> list = trainImgIPage.getRecords();
        long total = trainImgPage.getTotal();

        JSONArray imgArray = new JSONArray();
        for (TrainImg trainImg : list) {
            JSONObject imgJson = new JSONObject();
            imgJson.put("id", trainImg.getId());
            imgJson.put("imgName1", trainImg.getImgNameOne());
            imgJson.put("imgName2", trainImg.getImgNameTwo());
            imgJson.put("imgUrl1", trainImg.getImgUrlOne());
            imgJson.put("imgUrl2", trainImg.getImgUrlTwo());
            imgJson.put("plotList1", JSONArray.parseArray(trainImg.getImgPositionOne()));
            imgJson.put("plotList2", JSONArray.parseArray(trainImg.getImgPositionTwo()));
            imgJson.put("updateTime", sdf.format(trainImg.getUpdateTime()));
            User user = userMapper.selectById(trainImg.getCreatePerson());
            if (ObjectUtil.isNotNull(user)) {
                imgJson.put("userName", user.getName());
            } else {
                imgJson.put("userName", "该用户已删除");
            }
            imgArray.add(imgJson);
        }
        JSONObject imgReJson = new JSONObject();
        imgReJson.put("imgList", imgArray);
        imgReJson.put("pageAll", Math.ceil(total * 1.0 / Long.valueOf(pageSize)));
        imgReJson.put("pageNum", pageNum);
        imgReJson.put("pageSize", pageSize);
        imgReJson.put("total", total);
        return JSON.toJSONString(R.data(imgReJson));
    }

    @Override
    public String imgUpload(JSONObject jsonObject, HttpServletRequest request) {
        //jsonobject解析获取图片地址1
        String imgUrl1 = jsonObject.getString("imgUrl1");
        //jsonobject解析获取图片地址2
        String imgUrl2 = jsonObject.getString("imgUrl2");
        //jsonobject解析获取名称1
        String imgName1 = jsonObject.getString("imgName1");
        //jsonobject解析获取名称2
        String imgName2 = jsonObject.getString("imgName2");
        //jsonobject解析获取标绘1
        String plotList1 = jsonObject.getString("plotList1");
        //jsonobject解析获取标绘2
        String plotList2 = jsonObject.getString("plotList2");
        //jsonobject解析获取标识
        String id = jsonObject.getString("id");

        TrainImg trainImg = new TrainImg();

        if (StringUtils.isNotEmpty(id) && !id.equals("0")) {
            trainImg.setId(id);
        } else {
            int m = 0;
            Integer max = trainImgMapper.selectSortMax();
            if (null != max) {
                m = max;
            }
            trainImg.setSort(m + 1);
            trainImg.setCreatePerson(redisUseService.getUserId(request.getHeader("Id")));
        }

        trainImg.setImgNameOne(imgName1);
        trainImg.setImgPositionOne(plotList1);
        trainImg.setImgUrlOne(imgUrl1);
        trainImg.setImgNameTwo(imgName2);
        trainImg.setImgUrlTwo(imgUrl2);
        trainImg.setImgPositionTwo(plotList2);
        trainImgService.saveOrUpdate(trainImg);
        return JSON.toJSONString(R.success("操作成功"));
    }

    @Override
    public String plotEdit(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String id = jsonObject.getString("id");
        //jsonobject解析获取图片1
        String img1 = jsonObject.getString("img1");
        //jsonobject解析获取图片2
        String img2 = jsonObject.getString("img2");

        TrainImg trainImg = trainImgService.getById(id);

        JSONObject img1Json = JSONObject.parseObject(img1);
        String plot1 = img1Json.getString("plotList");
        JSONObject img2Json = JSONObject.parseObject(img2);
        String plot2 = img2Json.getString("plotList");
        if (null != trainImg) {
            trainImg.setImgPositionOne(plot1);
            trainImg.setImgPositionTwo(plot2);
            trainImgService.saveOrUpdate(trainImg);
            return "{\"msg\":\"操作成功\",\"code\":200,\"data\":{},\"success\":true}";
        } else {
            return JSON.toJSONString(R.success("无数据"));
        }
    }

    @Override
    public String imgDelete(JSONObject jsonObject) {
        //jsonobject解析获取标识
        JSONArray ids = jsonObject.getJSONArray("ids");
//        String idString = JSONObject.toJSONString(ids, SerializerFeature.WriteClassName);
//        List<String> idList = JSONObject.parseArray(idString, String.class);
//        if (idList.size() > 0) {
//            trainImgService.removeByIds(idList);
//        }
        if (CollectionUtil.isNotEmpty(ids)) {
            for (int i = 0; i < ids.size(); i++) {
                String id = ids.getString(i);
                TrainImg trainImg = trainImgService.getById(id);
                if (ObjectUtil.isNotNull(trainImg)) {
                    trainImgService.removeById(trainImg.getId());
                    trainImgMapper.updateSort(trainImg.getSort());
                }
            }
        }
        return JSON.toJSONString(R.success("操作成功"));
    }

}
